import { utils } from "./Utils";



const {ccclass, property} = cc._decorator;

/**
 *  game_jumps 
 *  {
 *      "app_id": "wxe42820321dca02f3",
 *      "path": "pages/index/index",
 *      "icon": ""
 *  }
 */

@ccclass
export default class TryGameNode extends cc.Component 
{

    @property({type: cc.Sprite})
    gameIcon: cc.Sprite = null;

    _gameJumpInterval: number = 0;
    _jumpInfo: any = null;
    _index: number = 0;
    _jumping: boolean = false; // 控制是否在跳转

    _init(){
        if(utils.wechatTool && utils.wechatTool.configData && utils.wechatTool.configData.game_jumps && utils.wechatTool.configData.game_jump_interval){
            this._jumpInfo = utils.wechatTool.configData.game_jumps;
            this._gameJumpInterval = utils.wechatTool.configData.game_jump_interval/1000;
        }
    }

    onEnable()
    {
        this._init();

        this.schedule(this.jump, this._gameJumpInterval);
        this.node.on(cc.Node.EventType.TOUCH_START, (event)=>{
            if(utils.wechatTool){
                if(this._jumpInfo[this._index] && this._jumpInfo[this._index].app_id){
                    utils.wechatTool.navigateToMiniProgram(this._jumpInfo[this._index].app_id);
                }
            } 
        }, this);
    }

    onDisable()
    {
        this.node.targetOff(this);
    }

    jump()
    {
        if(this._jumping) return;

        this._jumping = true;

        this._index = this._index + 1;
        if(this._index >= this._jumpInfo.length)
        {
            this._index = 0;
        }

        let self = this;
        let remoteUrl = this._jumpInfo[this._index].icon;
        cc.loader.load(remoteUrl, function (err, texture) {
            if(err)
            {
                cc.error(err);
            }
            else
            {   
                self.gameIcon.spriteFrame = new cc.SpriteFrame(texture);
            }

            self._jumping = false;
        });
    }

    public show(){
        this.node.active = true;
    }

    public hide(){
        this.node.active = false;
    }


    
}
